package cn.icebreak.cartoon.base;

import android.support.annotation.LayoutRes;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.HashMap;
import java.util.List;

/**
 * Description: RecyclerViewAdapter的通用抽象类，可以在外部操作item中每一个控件的点击事件
 * Created by crx on 2016/6/28.
 */
public abstract class CommExRecyclerViewAdapter<T, K extends BaseRecyclerViewHolder> extends RecyclerView.Adapter<K> {
    private List<T> mList;
    private HashMap<Integer, onItemClickListener> clickMap;//用来存放item中的某个控件的id和点击事件

    public CommExRecyclerViewAdapter(List<T> list) {
        mList = list;
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    @Override
    final public K onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(getLayoutRes(), parent, false);
        return createViewHolder(view);
    }


    abstract public @LayoutRes
    int getLayoutRes();


    abstract public K createViewHolder(View view);

    @Override
    final public void onBindViewHolder(K holder, int position) {
        addAllItemClickListener(holder.itemView, position, mList.get(position));
        bindViewHolder(holder, position, mList.get(position));
    }


    abstract public void bindViewHolder(K holder, int position, T bean);


    public void removeItem(int positin) {
        mList.remove(positin);
        notifyItemRemoved(positin);
    }

    public void addItem(int position, T value) {
        mList.add(position, value);
        notifyItemInserted(position);
    }

    private void addAllItemClickListener(final View itemView, final int position, final Object value) {
        if (clickMap != null && clickMap.size() > 0) {
            for (int id : clickMap.keySet()) {
                final View clickedView = itemView.findViewById(id);
                final onItemClickListener itemClickListener = clickMap.get(id);
                if (clickedView != null) {
                    clickedView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            itemClickListener.onClickListener(itemView, clickedView, position, value);
                        }
                    });
                }
            }
        }
    }

    /**
     * 设置item中某个控件的点击监听
     *
     * @param itemViewId        控件id
     * @param itemClickListener
     */
    public void setOnItemClickListener(int itemViewId, onItemClickListener itemClickListener) {
        if (clickMap == null) {
            clickMap = new HashMap<>();
        }
        clickMap.put(itemViewId, itemClickListener);
    }

    public interface onItemClickListener {
        void onClickListener(View itemView, View clickedView, int position, Object value);
    }


}
